package myJs

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.{_}
import myJs.myPkg.jquery._
import org.scalajs.dom.{Element, FormData, XMLHttpRequest, document}
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/15
 */
@JSExportTopLevel("BatchPredict")
object BatchPredict {

  def clearFile = {
    val curJq = $("#file")
    curJq.fileinput("clear")
    val bv = $("#form").bv
    bv.revalidateField(curJq)
  }

  @JSExport("myRun")
  def myRun = {
    val formJq = $("#form")
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", "正在检查文件",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", `class` := "runningImage",
          width := 30, height := 20
        )
      ).toString
      val layerOptions = LayerOptions.skin("layui-layer-molv").closeBtn(0).title(zhInfo).btn(js.Array())
      val index = layer.alert(element, layerOptions)
      $("#prompt").text("正在上传文件")
      val formData = new FormData(formJq(0).toHTMLFormElement)
      $("#tableResult,#result").hide()
      val xhr = new XMLHttpRequest
      val url = g.jsRoutes.controllers.PredictController.batchPredict().url.toString
      xhr.open("post", url)
      xhr.upload.onprogress = Utils.progressHandlingFunction
      xhr.timeout = 60000
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val rs = xhr.responseText.toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (!valid) {
            Swal.swal(SwalOptions.title("Error").text(rs.myGet("message")).`type`("error"))
            clearFile
            $("#tableResult").hide()
            $("#result").hide()
          } else {
            $("#missionTable").bootstrapTable("load", rs("array"))
            $("#tableResult").show()
          }
        }
      }
      xhr.ontimeout = (e) => {
        layer.close(index)
        Swal.swal(SwalOptions.title("错误").text("运行时间过长，请刷新页面!").`type`("error"))
      }
      xhr.onerror = (e) => {
        println(e)
        layer.close(index)
        Swal.swal(SwalOptions.title("错误").text("运行时间过长，请刷新页面!").`type`("error"))
      }

      xhr.send(formData)

    }

  }

}
